#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
class Solution {
public:

    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        int m = mat.size(), n = mat[0].size();
        vector<vector<int>> dis(m, vector<int>(n, -1));
        queue<pair<int, int>> Q;
        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                if (mat[i][j] == 0)
                {
                    Q.emplace(i, j);
                    dis[i][j] = 0;
                }
            }
        }
        while (!Q.empty())
        {
            auto [a, b] = Q.front();
            Q.pop();
            int dics[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
            for (auto dic : dics)
            {
                int x = a + dic[0], y = b + dic[1];
                if (x >= 0 && x < mat.size() && y >= 0 && y < mat[0].size() && dis[x][y] == -1 && mat[x][y])
                {
                    Q.emplace(x, y);
                    dis[x][y] = dis[a][b] + 1;
                }
            }
        }
        return dis;
    }
};
